package cn.sunchis.demo.es.repository;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity;
import org.springframework.data.elasticsearch.repository.support.AbstractElasticsearchRepository;
import org.springframework.data.elasticsearch.repository.support.ElasticsearchEntityInformation;
import org.springframework.data.elasticsearch.repository.support.MappingElasticsearchEntityInformation;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import cn.sunchis.demo.es.model.Book;

@Repository
public class BookRepositoryImpl extends AbstractElasticsearchRepository<Book, String> implements BookRepository {
//	public BookRepositoryImpl(ElasticsearchOperations elasticsearchOperations) {
//		super(elasticsearchOperations);
//	}
	
	@Autowired
    private ElasticsearchOperations elasticsearchOperations;
	
	public BookRepositoryImpl() {
		
	}
	
	@PostConstruct
	private void init() {
		this.entityClass = Book.class;
		setElasticsearchOperations(elasticsearchOperations);
		this.entityInformation = entityInformationFor(elasticsearchOperations, Book.class, String.class);
	}
	
//	public BookRepositoryImpl(ElasticsearchOperations elasticsearchOperations) {
//		this((ElasticsearchEntityInformation<Book, String>)entityInformationFor(elasticsearchOperations, Book.class, null), elasticsearchOperations);
//	}
	
//	private BookRepositoryImpl(ElasticsearchEntityInformation<Book, String> metadata, ElasticsearchOperations elasticsearchOperations) {
//		super(metadata, elasticsearchOperations);
//		
//		this.entityClass = metadata.getJavaType();
//		this.elasticsearchOperations = elasticsearchOperations;
//		this.entityInformation = metadata;
//	}
	
	@SuppressWarnings("unchecked")
	private static ElasticsearchEntityInformation<Book, String> entityInformationFor(ElasticsearchOperations elasticsearchOperations, Class<?> pojoType, Class<?> idType) {
		ElasticsearchPersistentEntity<Book> entity = (ElasticsearchPersistentEntity<Book>) elasticsearchOperations.getElasticsearchConverter().getMappingContext().getPersistentEntity(pojoType);
		Assert.notNull(entity, "Entity must not be null!");

		ElasticsearchEntityInformation<Book, String> entityInformation = new MappingElasticsearchEntityInformation<>(entity);

		//boolean isAssignable = ClassUtils.isAssignable(Persistable.class, entity.getType());
		//return ClassUtils.isAssignable(Persistable.class, entity.getType())
		//		? new PersistableMongoEntityInformation<T, ID>(entityInformation) : entityInformation;
		return entityInformation;
	}
	
	@Override
	protected String stringIdRepresentation(String id) {
		return id;
	}

}
